﻿<FluentGrid Justify="JustifyContent.FlexStart" Spacing="3">
    <FluentGridItem xs="12" sm="6">
        <h5>List 1</h5>
        <FluentSortableList Id="clone1" Group="cloning" Clone="true" OnUpdate="@SortListOne" OnRemove="@ListOneRemove" Items="@items1" Context="item">
            <ItemTemplate>@item.Name</ItemTemplate>
        </FluentSortableList>
    </FluentGridItem>
    <FluentGridItem xs="12" sm="6">
        <h5>List 2</h5>
        <FluentSortableList Id="clone2" Group="cloning" Clone="true" OnUpdate="@SortListTwo" OnRemove="@ListTwoRemove" Items="@items2" Context="item">
            <ItemTemplate>@item.Name</ItemTemplate>
        </FluentSortableList>
    </FluentGridItem>
</FluentGrid>

@code {
    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; } = "";

        public bool Disabled { get; set; } = false;
    }

    public List<Item> items1 = Enumerable.Range(1, 10).Select(i => new Item { Id = i, Name = $"Item {i}" }).ToList();

    public List<Item> items2 = Enumerable.Range(11, 10).Select(i => new Item { Id = i, Name = $"Item {i}" }).ToList();

    private void ListOneRemove(FluentSortableListEventArgs args)
    {
        if (args is null)
        {
            return;
        }

        // get the item at the old index in list 1
        var item = items1[args.OldIndex];

        var clone = item;

        // add it to the new index in list 2
        items2.Insert(args.NewIndex, clone);
    }

    private void ListTwoRemove(FluentSortableListEventArgs args)
    {
        if (args is null)
        {
            return;
        }

        // get the item at the old index in list 2
        var item = items2[args.OldIndex];

        // make a copy
        var clone = item;

        // add it to the new index in list 1
        items1.Insert(args.NewIndex, clone);
    }

    private void SortListOne(FluentSortableListEventArgs args)
    {
        if (args is null || args.OldIndex == args.NewIndex)
        {
            return;
        }

        var oldIndex = args.OldIndex;
        var newIndex = args.NewIndex;

        var items = this.items1;
        var itemToMove = items[oldIndex];
        items.RemoveAt(oldIndex);

        if (newIndex < items.Count)
        {
            items.Insert(newIndex, itemToMove);
        }
        else
        {
            items.Add(itemToMove);
        }
    }

    private void SortListTwo(FluentSortableListEventArgs args)
    {
        if (args is null || args.OldIndex == args.NewIndex)
        {
            return;
        }

        var oldIndex = args.OldIndex;
        var newIndex = args.NewIndex;

        var items = this.items2;
        var itemToMove = items[oldIndex];
        items.RemoveAt(oldIndex);

        if (newIndex < items.Count)
        {
            items.Insert(newIndex, itemToMove);
        }
        else
        {
            items.Add(itemToMove);
        }
    }
}
